﻿using System;
using System.Buffers.Binary;
using System.Buffers.Text;
using System.Collections.Generic;
using System.IO;
using System.Net.Http.Headers;
using System.Text;
using ZGRemote.Common.Utils;

namespace ZGRemote.Common.Builder
{
    public class Builder
    {
        private static int tag = 9527;

        public static bool SaveData(string path, BuilderData data)
        {
            if(!File.Exists(path)) return false;
            using (var stream = File.OpenWrite(path))
            {
                using(var bw = new BinaryWriter(stream))
                {
                    bw.BaseStream.Position = bw.BaseStream.Length;
                    var bData = SerializeUtil.Serialize(data);
                    bw.Write(bData);
                    bw.Write(bData.Length);
                    bw.Write(tag);
                }
            }
            return true;
        }

        public static bool LoadData(string path, out BuilderData data)
        {
            data = null;
            using(var stream = File.OpenRead(path))
            {
                using(var br = new BinaryReader(stream))
                {
                    br.BaseStream.Position = br.BaseStream.Length - 4;
                    int temp = br.ReadInt32();
                    if(temp != tag) return false;
                    br.BaseStream.Position = br.BaseStream.Length - 8;
                    temp = br.ReadInt32();
                    br.BaseStream.Position = br.BaseStream.Length - 8 - temp;
                    data = SerializeUtil.Deserialize<BuilderData>(br.ReadBytes(temp));
                    return true;
                }
            }
        }
    }
}
